import { fileUploadControllerUploadFile } from "@/app/servers/api/fileUpload";
import { UploadOutlined } from "@ant-design/icons";
import { Button, message, Upload, UploadProps } from "antd";

export interface CustomUploadProps extends Omit<UploadProps, "onChange"> {
  value?: API.CustomeFile;
  onChange?: (value?: API.CustomeFile) => void;
  maxSize?: number;
}
export const SingleUpload: React.FC<CustomUploadProps> = ({
  value,
  onChange,
  maxSize = 5,
  ...uploadProps
}) => {
  const fileList = value
    ? [{ value, url: value.href, uid: value.name, name: value.name }]
    : [];
  return (
    <div>
      <Upload
        listType="picture-card"
        accept="image/png, image/jpg, image/jpeg"
        maxCount={1}
        showUploadList={{
          showPreviewIcon: true,
          showRemoveIcon: true,
        }}
        fileList={fileList}
        multiple={false}
        beforeUpload={(file) => {
          const isLtMaxSize = file.size / 1024 / 1024 < maxSize;
          if (!isLtMaxSize) {
            message.error(`文件大小不能超过 ${maxSize}MB！`);
            return false;
          }
          return true;
        }}
        customRequest={async (options) => {
          const { file, onSuccess } = options;
          const formData = new FormData();
          formData.append("file", file);
          try {
            const response = await fileUploadControllerUploadFile({
              data: formData,
            });
            if (response.data) {
              message.success("上传成功");
              onSuccess?.(response.data);
              onChange?.(response.data);
            } else {
              throw new Error("Upload failed");
            }
          } finally {
          }
        }}
        onRemove={() => {
          onChange?.();
        }}
        {...uploadProps}
      >
        <div>
          {uploadProps.listType === "text" ? (
            <Button icon={<UploadOutlined />}>Upload</Button>
          ) : (
            <div style={{ marginTop: 8 }}>点击上传</div>
          )}
        </div>
      </Upload>
    </div>
  );
};
